package com.usian.admin.filter;

import com.usian.admin.utils.AppJwtUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang3.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
@Component
@Log4j2
public class AuthorizeFilter implements GlobalFilter, Ordered {

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //1.获取当前的请求体和响应体
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        //2.是否要鉴权 要放行登录请求
        if (request.getURI().getPath().contains("/login/in")==true){
            return  chain.filter(exchange);
        }

        //3.验证token是否存在
        HttpHeaders headers = request.getHeaders();
        String token = headers.getFirst("token");
        if (StringUtils.isBlank(token)){
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }

       try {
           //4.验证token是否有效
           Claims claims = AppJwtUtil.getClaimsBody(token);
           int result = AppJwtUtil.verifyToken(claims);
           if (result==-1||result==0){
               //有效
               //5.token解密
               Integer userId =(Integer) claims.get("id");
               //6.解密后的token带入下个请求头
               ServerHttpRequest serverHttpRequest = request.mutate().headers(httpHeaders -> {
                   httpHeaders.add("userId", userId + "");
               }).build();
               exchange.mutate().request(serverHttpRequest).build();

           }
       }catch (Exception e){
           response.setStatusCode(HttpStatus.INTERNAL_SERVER_ERROR);
           return response.setComplete();
       }
        //7.放行
        return  chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
